package com.ideaplugin.datamanager.config;

import cn.dev33.satoken.exception.NotLoginException;
import com.ideaplugin.datamanager.model.common.BaseResult;
import com.ideaplugin.datamanager.model.common.CommonResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

/**
 * @author 赵静波
 * @date 2021-02-10 16:39:47
 */
@RestControllerAdvice
@Slf4j
public class GlobeException {

    @ExceptionHandler
    @ResponseBody
    public BaseResult exception(Exception exception) {
        log.error("{}", exception);
        return new BaseResult().setErrorMessage("9851", "数据异常");
    }

    @ExceptionHandler
    @ResponseBody
    public BaseResult exception(NotLoginException exception) {
        log.error("{}", exception);
        return new BaseResult().setErrorMessage(CommonResultCode.AUTHENTICATION_EXCEPTION.code, "登录失效，请重新登录");
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public BaseResult handle(MethodArgumentNotValidException e) {
        log.error("{}", e);
        final FieldError fieldError = e.getBindingResult().getFieldError();

        return new BaseResult().setErrorMessage(CommonResultCode.ILLEGAL_PARAM.code, fieldError.getField() + fieldError.getDefaultMessage());
    }

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public BaseResult handle(BindException e) {
        log.error("{}", e);
        final FieldError fieldError = e.getBindingResult().getFieldError();
        return new BaseResult().setErrorMessage("9851", fieldError.getField() + fieldError.getDefaultMessage());

    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public BaseResult handle(ConstraintViolationException e) {
        log.error("{}", e);
        StringBuffer sb = new StringBuffer();
        for (ConstraintViolation<?> violation : e.getConstraintViolations()) {
            sb.append(violation.getMessage());
        }
        return new BaseResult().setErrorMessage("9851", sb.toString());
    }
}
